package com.llyb.chap03;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class printNum{
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private Integer flag = 1;

    public void print5() throws InterruptedException {
        lock.lock();
        try {
            while (flag!=1){
                condition1.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+"---- i:"+i);
            }

            flag = 2;
            condition2.signalAll();
        } finally {
            lock.unlock();
        }

    }

    public void print10() throws InterruptedException {
        lock.lock();
        try {
            while (flag!=2){
                condition2.await();
            }
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+"=============== i:"+i);
            }

            flag = 3;
            condition3.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public void print15() throws InterruptedException {
        lock.lock();
        try {
            while (flag!=3){
                condition3.await();
            }
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+"************************ i:"+i);
            }

            flag = 1;
            condition1.signalAll();
        } finally {
            lock.unlock();
        }
    }


}

public class CyclePrint10 {


    public static void main(String[] args) {

        printNum printNum = new printNum();
        new Thread(()->{
            try {
                for (int i = 0; i < 5; i++) {
                    printNum.print5();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"AA").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 5; i++) {
                    printNum.print10();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"BB").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 5; i++) {
                    printNum.print15();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"CC").start();
    }
}
